<template>
  <div class="video-container">
    <video
      v-if="videoUrl"
      controls
      class="video-player"
      disablePictureInPicture
      @timeupdate="handleTimeUpdate"
      @loadedmetadata="handleVideoLoaded"
      ref="videoRef"
    >
      <source :src="videoUrl" type="video/mp4" />
      您的浏览器不支持视频播放。
    </video>
  </div>
</template>

<script setup>
// ... existing code ...
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";

const route = useRoute();
const videoUrl = ref("");
const videoRef = ref(null);
let lastCurrentTime = 0;
const isInitialSeek = ref(true);

// 保存播放进度
const saveVideoProgress = (currentTime) => {
  const fileName = route.query.url;
  if (fileName) {
    const progress = currentTime / videoRef.value.duration;
    localStorage.setItem(
      `video-progress-${fileName}-${route.query.id}`,
      progress
    );
    // 发送自定义事件通知进度更新
    window.dispatchEvent(
      new CustomEvent("video-progress-update", {
        detail: {
          fileName,
          progress,
        },
      })
    );
  }
};

// 获取保存的播放进度
const getVideoProgress = (fileName) =>
  parseFloat(
    localStorage.getItem(`video-progress-${fileName}-${route.query.id}`)
  ) || 0;

const handleTimeUpdate = (event) => {
  const video = event.target;
  if (isInitialSeek.value) {
    lastCurrentTime = video.currentTime;
    isInitialSeek.value = false;
    return;
  }

  if (Math.abs(video.currentTime - lastCurrentTime) > 1) {
    video.currentTime = lastCurrentTime;
  } else {
    lastCurrentTime = video.currentTime;
    saveVideoProgress(video.currentTime);
  }
};

// 视频加载完成后设置上次播放位置
const handleVideoLoaded = () => {
  if (videoRef.value) {
    const fileName = route.query.url;
    const savedTime = getVideoProgress(fileName);
    if (savedTime) {
      console.log("savedTime", savedTime);
      isInitialSeek.value = true;
      videoRef.value.currentTime = savedTime * videoRef.value.duration;
    }
  }
};

onMounted(() => {
  const fileName = route.query.url;
  if (fileName) {
    videoUrl.value = `http://localhost:9080/elearning/video/stream?fileName=${encodeURIComponent(
      fileName
    )}&start=${getVideoProgress(fileName)}`;
  }
});

// ... existing code ...
</script>

<style scoped>
.video-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.video-player {
  height: calc(100vh - 100px);
  max-width: 1200px;
  margin: 20px auto;
  display: block;
}
</style>
